<?php

namespace App\Models\System;

use App\Models\Model;

class Scale extends Model
{
    protected $table = 'scales';
    protected $guarded = [];
    protected $appends = [
        'tier_num',
        'files_array'
    ];

    public function term()
    {
        return $this->hasOne(Term::class, 'id', 'term_id');
    }  

    public function detail()
    {
        return $this->hasMany(ScaleDetail::class, 'scale_id', 'id')->wherePid(0)->with('child');
    }

    public function tableDetail()
    {
        return $this->hasMany(ScaleDetail::class, 'scale_id', 'id')
            ->whereIsEnd(1)
            ->orderBy('top_id', 'asc')
            ->orderBy('sort', 'asc')
            ->orderBy('pid', 'asc')
            ->with('parent');
    }
    
    public function getTierNumAttribute()
    {
        if (array_key_exists('tier_code', $this->attributes)){
            $code = $this->attributes['tier_code'];

            if(!$code){
                return 0;
            }

            return (int) $code;
        }

        return [];
    }

    public function getFilesArrayAttribute()
    {
        if (array_key_exists('files', $this->attributes)){
            $materials = $this->attributes['files'];

            if(!$materials){
                return [];
            }

            return json_decode($materials, true);
        }

        return [];
    }

    
}
